package com.mbbb.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.mbbb.yygh.enums.PaymentTypeEnum;
import com.mbbb.yygh.enums.RefundStatusEnum;
import com.mbbb.yygh.model.order.OrderInfo;
import com.mbbb.yygh.model.order.PaymentInfo;
import com.mbbb.yygh.model.order.RefundInfo;
import com.mbbb.yygh.orders.service.OrderInfoService;
import com.mbbb.yygh.orders.service.PaymentInfoService;
import com.mbbb.yygh.orders.service.RefundInfoService;
import com.mbbb.yygh.orders.service.WeixinService;
import com.mbbb.yygh.orders.utils.ConstantPropertiesUtils;
import com.mbbb.yygh.orders.utils.HttpClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    //微信退款
    @Override
    public Boolean refund(Long orderId) {
        //1.根据订单号查询订单数据支付记录（交易号 和 trade_no）
        PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId);

        //2.向退款记录表中添加数据（状态：退款中-1）
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);

        //3.封装微信退款接口需要的参数
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee","1"); //总金额
        paramMap.put("refund_fee","1"); //退款金额

        try {
            //4.使用httpclient请求微信退款接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus()); //退款成功
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //根据订单号和支付类型查询支付状态
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {
        //1.根据订单号查询订单数据
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        //2.封装微信接口需要的参数
        Map paramMap = new HashMap();
        paramMap.put("appid",ConstantPropertiesUtils.APPID); //公众号id
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER); //商户号
        paramMap.put("out_trade_no",orderInfo.getOutTradeNo()); //交易号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr()); //微信要求传随机数
        try {
            //3.使用httpclient调用微信支付状态接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam((WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY)));
            client.setHttps(true);
            client.post();

            //4.返回第三方的数据，转成Map
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态返回：xml = " + xml);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //生成支付二维码
    @Override
    public Map<String, Object> createNativeWx(Long orderId) {

        //1.根据订单号查询订单信息
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);

        //2.将订单信息添加到支付表中（支付状态：支付中）
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        try {
            //3.封装二维码生成接口所需要的数据
            Map paramMap = new HashMap();
            //公众号id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            //商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            //传递随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //微信扫描支付二维码，微信显示内容
            Date reserveDate = orderInfo.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊于" + orderInfo.getHosname() + "-" + orderInfo.getDepname();
            paramMap.put("body", body);
            //订单交易号
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            //支付金额
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//TODO 为了测试 支付0.01元
            //客户端ip地址
            paramMap.put("spbill_create_ip", "127.0.0.1");
            //回调地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            //二维码类型  NATIVE
            paramMap.put("trade_type", "NATIVE");

            //4.使用httpclient请求微信二维码生成接口，返回需要的数据
            //设置请求路径
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置向路径传递的参数（xml），我们的paramMap（map），使用商户key编码
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            //设置https
            client.setHttps(true);
            //发送请求
            client.post();

            //请求微信二维码生成接口后，返回数据（xml）
            String xml = client.getContent();
            System.out.println("xml = " + xml);

            //xml --> map
            //wxMap集合中包含微信支付二维码接口
            Map<String, String> wxMap = WXPayUtil.xmlToMap(xml);

            //封装返回结果集
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", wxMap.get("result_code"));
            map.put("codeUrl", wxMap.get("code_url"));
            if(null != map.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
